package org.learn.phase3.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class SocketTCP01Server {
    public static void main(String[] args) throws IOException {
        //1.在本机的9999端口监听，等待连接
        //要求9999没有被占用
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("等待连接");
        //2.当有客户端连接9999端口时，程序会阻塞，等待连接
        //如果有客户端连接，则会返回Socket对象，程序继续
        Socket socket = serverSocket.accept();

        System.out.println("服务端 socket = " + socket.getClass());
        //3.通过socket.getInputStream() 读取客户端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        //4.io读取
//        byte[] buf = new byte[1024];
//        int readLen = 0;
//        while ((readLen = inputStream.read(buf)) != -1){
//            System.out.println(new String(buf,0,readLen));//根据读取到的实际长度，显示内容
//        }

        //4.io读取，用字符流，
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);//输出


        //5.获取socket 相关联的输出流
        OutputStream outputStream = socket.getOutputStream();
//        outputStream.write("hello,client" .getBytes());
//        //设置写入标记
//        socket.shutdownOutput();

        //使用字符流的方式回复信息
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,Client 字符流");
        bufferedWriter.newLine();//换行
        bufferedWriter.flush();//刷新


        //6.关闭流和socket
        outputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();

    }
}
